package com.franklin.java.api.psi.comment;

import com.franklin.plugins.common.collection.PrettyArrayList;
import com.franklin.plugins.common.utils.DataCheckUtils;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.util.PsiTreeUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @author Franklin
 * @since 2021/9/16 15:47
 */
class PsiClassCommentResolver extends AbstractPsiCommentResolver<PsiClass> {
    @Override
    public String resolveComment(PsiClass psiClass) {
        List<PsiComment> psiCommentList = PsiTreeUtil.getChildrenOfTypeAsList(psiClass, PsiComment.class);
        if (DataCheckUtils.isEmpty(psiCommentList)){
            return "";
        }
        for (PsiComment psiComment : psiCommentList) {
            if (psiComment instanceof PsiDocComment){
                PsiDocComment psiDocComment = (PsiDocComment) psiComment;
                return psiDocComment.getText();
            }
        }
        return "";
    }

    @Override
    public String resolveSimpleComment(PsiClass psiClass) {
        List<PsiComment> psiCommentList = PsiTreeUtil.getChildrenOfTypeAsList(psiClass, PsiComment.class);
        if (DataCheckUtils.isEmpty(psiCommentList)){
            return "";
        }
        StringBuilder commentBuilder = new StringBuilder();
        for (PsiComment psiComment : psiCommentList) {
            if (psiComment instanceof PsiDocComment){
                PsiDocComment psiDocComment = (PsiDocComment) psiComment;
                PsiElement[] descriptionElements = psiDocComment.getDescriptionElements();
                for (PsiElement descriptionElement : descriptionElements) {
                    String text = descriptionElement.getText();
                    if (StringUtils.isNotBlank(text)){
                        commentBuilder.append(text.trim());
                    }
                }
            }
        }
        return commentBuilder.toString();
    }
}
